package middleware

import (
	"time"

	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
)

// AuditLogMiddleware 审计日志中间件
func AuditLogMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		start := time.Now()
		c.Next()
		status := c.Writer.Status()

		// 仅在请求失败时记录日志
		if status >= 400 {
			// 记录审计日志
			duration := time.Since(start)
			zap.L().Info("Request processed",
				zap.String("method", c.Request.Method),
				zap.String("path", c.Request.URL.Path),
				zap.Int("status", c.Writer.Status()),
				zap.Duration("duration", duration),
			)
		}
	}
}

// KeyRotationMiddleware 密钥轮转中间件
func KeyRotationMiddleware(rotationInterval time.Duration, keyStore KeyStore) gin.HandlerFunc {
	var lastRotation time.Time
	var currentKey string

	// 初始化密钥
	key, err := keyStore.GetCurrentKey()
	if err != nil {
		zap.L().Fatal("Failed to initialize key rotation", zap.Error(err))
	}
	currentKey = key

	return func(c *gin.Context) {
		// 检查是否需要轮转密钥
		if time.Since(lastRotation) > rotationInterval {
			newKey, err := keyStore.RotateKey()
			if err != nil {
				zap.L().Error("Failed to rotate key", zap.Error(err))
			} else {
				currentKey = newKey
				lastRotation = time.Now()
				zap.L().Info("Key rotated", zap.String("newKey", newKey))
			}
		}

		// 将当前密钥设置到上下文中
		c.Set("currentKey", currentKey)
		c.Next()
	}
}

// KeyStore 密钥存储接口
type KeyStore interface {
	GetCurrentKey() (string, error)
	RotateKey() (string, error)
}

// ExampleKeyStore 示例密钥存储实现
type ExampleKeyStore struct{}

func (ks *ExampleKeyStore) GetCurrentKey() (string, error) {
	// 返回当前密钥
	return "current_key", nil
}

func (ks *ExampleKeyStore) RotateKey() (string, error) {
	// 生成新密钥
	newKey := "new_key_" + time.Now().Format(time.RFC3339)
	return newKey, nil
}
